#include "rgbvideowidget.h"
#include "ui_rgbvideowidget.h"
#include "rgbcapture.h"
#include "singleton.h"

#include <QMessageBox>
RgbVideoWidget::RgbVideoWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::RgbVideoWidget)
{
    ui->setupUi(this);
    rgbCapture = RgbCaptureInstance;
    connect(rgbCapture, &RgbCapture::error, this, &RgbVideoWidget::handleError);
    connect(rgbCapture, &RgbCapture::clearFrame, ui->videoWidget, &VideoWidget::clearFrame);
    //connect(rgbCapture, &RgbCapture::frameReady, ui->videoWidget, &VideoWidget::setFrame);

    connect(rgbCapture, &RgbCapture::started, this, &RgbVideoWidget::onDecoderStarted);
    connect(rgbCapture, &RgbCapture::stopped, this, &RgbVideoWidget::onDecoderStopped);
}

RgbVideoWidget::~RgbVideoWidget()
{
    delete ui;
}

void RgbVideoWidget::on_startButton_clicked()
{
    QString url = ui->urlLineEdit->text().trimmed();
    if (url.isEmpty()) {
        QMessageBox::warning(this, "警告", "请输入有效的RTSP URL");
        return;
    }

    ui->startButton->setEnabled(false);
    ui->stopButton->setEnabled(true);

    QMetaObject::invokeMethod(rgbCapture, [this, url]() {
        rgbCapture->start(url);
        }, Qt::QueuedConnection);

    // 更新按钮状态
    ui->startButton->setEnabled(false);
    ui->stopButton->setEnabled(true);
}


void RgbVideoWidget::on_stopButton_clicked()
{
    ui->startButton->setEnabled(true);
    ui->stopButton->setEnabled(false);

    QMetaObject::invokeMethod(rgbCapture, [this]() {
        rgbCapture->stop();
        }, Qt::QueuedConnection);
}

void RgbVideoWidget::onDecoderStarted()
{
    //ui->videoLabel->setText("正在接收视频...");
}

void RgbVideoWidget::onDecoderStopped()
{
    ui->startButton->setEnabled(true);
    ui->stopButton->setEnabled(false);
    //ui->videoLabel->setText("视频已停止");
}

void RgbVideoWidget::handleError(const QString& error)
{
    QMessageBox::critical(this, "错误", error);
    ui->startButton->setEnabled(true);
    ui->stopButton->setEnabled(false);
}

